package com.hdax.gulimall.product.exception;


import com.hdax.common.exception.BizCodeEnume;
import com.hdax.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;


/**
 * 全局异常处理处理
 */
@ControllerAdvice
@RestController
@Slf4j
public class GulimallExceptionController {




    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e){
        log.error("数据校验出现了问题");
        BindingResult bindingResult = e.getBindingResult();
        Map<String,String > map=new HashMap<>();
        //1、获取校验的错误结果
        //获取所有校验错误的字段
        bindingResult.getFieldErrors().forEach((item)->{
                //错误提示消息
            String defaultMessage = item.getDefaultMessage();
            //获取发生错误的属性名称
            String field = item.getField();
            map.put(field,defaultMessage);
        });
        return  R.error(BizCodeEnume.VALIE_EXCEPTION.getCode(),BizCodeEnume.VALIE_EXCEPTION.getMsg()).put("data",map);
    }

//    @ExceptionHandler(value = Throwable.class)
//    public R handlerException(){
//        return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(),BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
//    }
}
